﻿using System;
using System.Collections.Generic;
using System.Linq;  
using System.Text;
using System.Reflection.Emit;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Activation;
namespace WinnerCMS.CacheStorager
{
    public class AopProxy : RealProxy
    {
        public AopProxy(Type serverType)
            : base(serverType) { }

        public override IMessage Invoke(IMessage msg)
        {
            if (msg is IConstructionCallMessage)
            {
                IConstructionCallMessage constructCallMsg = msg as IConstructionCallMessage;
                IConstructionReturnMessage constructionReturnMessage = this.InitializeServerObject((IConstructionCallMessage)msg);
                RealProxy.SetStubData(this, constructionReturnMessage.ReturnValue);
                Console.WriteLine("Call constructor");
                return constructionReturnMessage;
            }
            else
            {
                IMethodCallMessage callMsg = msg as IMethodCallMessage;
                IMessage message;

                if (callMsg == null || (Attribute.GetCustomAttribute(callMsg.MethodBase, typeof(CacheAttribute))) == null)
                {
                    
                }
                else
                {
                }
                try
                {
                    object[] args = callMsg.Args;
                    object o = callMsg.MethodBase.Invoke(GetUnwrappedServer(), args);
                    message = new ReturnMessage(o, args, args.Length, callMsg.LogicalCallContext, callMsg);

                }
                catch (Exception e)
                {
                    message = new ReturnMessage(e, callMsg);
                }

                Console.WriteLine(message.Properties["__Return"].ToString());
                return message;
            }
        }
    }
}
